<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Controller;
use think\Request;

class Product extends Backend
{
    public function __construct()
    {
        parent::__construct();
        $this->ProductModel = model('Product.Product');
        $this->ProductTypeModel = model('Product.ProductType');
    }

    // 商品列表
    public function list()
    {
        // 分页
        $ProductList = $this->ProductModel->with('ProductType')
            ->paginate(5, false, ['query' => Request::instance()->param()]);

        // 条件搜索
        if ($this->request->isGet()) {
            $action = $this->request->param('action');
            if ($action == 'search') {
                $params = $this->request->param();
                if ($params['search'] == 'name') {
                    $ProductList = $this->ProductModel->where('name', 'LIKE', '%' . $params['name_text'] . '%')->paginate(
                        4,
                        false,
                        ['query' => Request::instance()->param()]
                    );
                }
            }
        }

        $navTitle = '商品管理';
        $navSmall = '商品列表';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            "ProductList" => $ProductList
        ]);
    }

    // 商品分类
    public function cate()
    {
        // 分页
        $TypeList = $this->ProductTypeModel->order('weigh')
            ->paginate(4, false, ['query' => Request::instance()->param()]);

        // 条件搜索
        if ($this->request->isGet()) {
            $action = $this->request->param('action');
            if ($action == 'search') {
                $params = $this->request->param();
                if ($params['search'] == 'name') {
                    $TypeList = $this->ProductTypeModel->where('name', 'LIKE', '%' . $params['name_text'] . '%')->paginate(
                        4,
                        false,
                        ['query' => Request::instance()->param()]
                    );
                }
            }
        }
        foreach ($TypeList as $item) {
            // halt($item['id']); // 分类id
            $res = $this->ProductModel->where('typeid', $item['id'])->select();
            // 获取对应帖子数量
            $num = count($res);
            // 添加属性
            $item['num'] = $num;
        }
        // halt($TypeList);
        $navTitle = '商品管理';
        $navSmall = '商品分类';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'TypeList' => $TypeList
        ]);
    }

    // 商品新增
    public function listAdd()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();

            $thumbs = upload('thumbs');
            if ($thumbs['code'] == 0) {
                $this->error($thumbs['msg']);
            }

            $data = [
                'name' => $params['name'],
                'typeid' => $params['cate'],
                'price' => $params['price'],
                'stock' => $params['stock'],
                'flag' => $params['flag'],
            ];
            $thumbs['data'] = str_replace("/uploads", "uploads", $thumbs['data']);
            $data['thumbs'] = '["' . $thumbs['data'] . '"]';
            $state = $this->ProductModel->validate('common/Product/Product')->save($data);

            if ($state == false) {
                @is_file('./' . $thumbs['data']) && unlink('./' . $thumbs['data']);
                $this->error($this->ProductModel->getError());
            } else {
                $this->success('添加商品成功${state}', url('/admin/product/list'));
            }
        }

        $type = $this->ProductTypeModel->select();
        return $this->fetch('', [
            'type' => $type
        ]);
    }

    // 删除商品
    public function listDel()
    {
        $proid = $this->request->param('id');
        $post = $this->ProductModel->find($proid);
        if (!$post) {
            $this->error('无法删除该商品');
        }
        $res = $this->ProductModel->destroy($proid);
        if ($res == false) {
            $this->error('删除商品失败');
        }
        $this->success('删除商品成功');
    }

    // 批量删除
    public function listDelAll()
    {
        $action = $this->request->param('action');
        if ($action == 'delAll') {
            $params = $this->request->param();
            $ids = implode(',', $params['list']);
            // halt($ids);
            // $res = $this->ProductModel->where("id in ($ids)")->delete();
            $res = $this->ProductModel->destroy($ids);
            // halt($res);
            if (!$res) {
                $this->error('批量删除失败');
            }
            $this->success("批量删除成功", null, url('/admin/product/list'), 2);
        }
    }

    // 商品编辑
    public function listEdit()
    {
        $id = $this->request->param('id');
        // halt($id);
        $pro = $this->ProductModel->find($id);
        if ($pro == null) {
            $this->error('该商品不存在，无法更新');
        }

        $type = $this->ProductTypeModel->select();

        if ($this->request->isPost()) {
            $params = $this->request->param();
            $data = [
                'id' => $id,
                'name' => $params['name'],
                'typeid' => $params['cate'],
                'price' => $params['price'],
                'stock' => $params['stock'],
                'flag' => $params['flag'],
            ];

            $thumbs = upload('thumbs');
            if ($thumbs == false) {
                $data['thumbs'] = $pro['thumbs'];
            } else if ($thumbs['code'] == 0) {
                $this->error($thumbs['msg']);
            }
            $thumbs['data'] = str_replace("/uploads", "uploads", $thumbs['data']);
            $data['thumbs'] = '["' . $thumbs['data'] . '"]';
            $state = $this->ProductModel->isUpdate(true)->save($data);
            if ($state == false) {
                @is_file('./' . $thumbs['data']) && unlink('./' . $thumbs['data']);
                $this->error('更新商品失败');
            } else {
                $pro['thumbs'] = ltrim($pro['thumbs'], '["');
                $pro['thumbs'] = rtrim($pro['thumbs'], '"]');
                @is_file('./' . $pro['thumbs']) && unlink('./' . $pro['thumbs']);
                $this->success('更新商品成功', url('admin/product/list'), null, 2);
            }
        }

        return $this->fetch('', [
            'pro' => $pro,
            'type' => $type
        ]);
    }

    // 分类删除
    public function cateDel()
    {
        $cateid = $this->request->param('id');
        $cate = $this->ProductTypeModel->find($cateid);
        if (!$cate) {
            $this->error('无法删除该分类');
        }
        $res = $this->ProductTypeModel->destroy($cateid);
        if ($res == false) {
            $this->error('删除分类失败');
        }
        $this->success('删除分类成功');
    }

    // 分类添加
    public function cateAdd()
    {
        $params = $this->request->param();
        $type = $this->ProductTypeModel->select();
        if ($this->request->isPost()) {

            $name = $params['name'];
            $typeName = $this->ProductTypeModel->where('name', $name)->find();
            if ($typeName) {
                $this->error('分类名称重复');
            }

            $cover = upload('cover');
            // halt($cover);
            if ($cover['code'] == 0) {
                $this->error($cover['msg']);
            }
            $data = [
                'name' => $params['name'],
                'weigh' => $params['weigh'],
                'cover' => $cover['data'],
            ];
            $state = $this->ProductTypeModel->validate('common/Product/ProductType')->save($data);
            if ($state == false) {
                @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
                $this->error($this->ProductTypeModel->getError());
            } else {
                @is_file('.' . $typeName['cover']) && unlink('.' . $typeName['cover']);
                $this->success('添加商品分类成功', url('/admin/product/cate'));
            }
        }
        return $this->fetch('', [
            'type' => $type
        ]);
    }

    // 分类编辑
    public function cateEdit()
    {
        $id = $this->request->param('id');
        $cate = $this->ProductTypeModel->find($id);
        if (!$cate) {
            $this->error('无法编辑该分类');
        }
        // halt($cate);
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $name = $params['name'];
            $type = $this->ProductTypeModel->where('name', $name)->find();
            if ($type && $type['name'] == $name) {
                $name = $type['name'];
            } else if ($type && $type['name'] != $name) {
                $this->error('分类名称重复');
            }

            $data = [
                'id' => $params['id'],
                'name' => $name,
                'weigh' => $params['weigh'],
            ];

            $cover = upload('cover');
            $data['cover'] = $cover['data'];

            if ($cover == false) {
                $data['cover'] = $type['cover'];
            } else if ($cover['code'] == 0) {
                $this->error($cover['msg']);
            }

            // halt($data);
            $state = $this->ProductTypeModel->isUpdate(true)->save($data);
            if ($state == false) {
                @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
                $this->error($this->ProductTypeModel->getError());
            } else {
                @is_file('.' . $type['cover']) && unlink('.' . $type['cover']);
                $this->success('更新商品分类成功', url('/admin/product/cate'));
            }
        }
        return $this->fetch('', [
            'cate' => $cate
        ]);
    }


    // 回收站
    public function recovery()
    {
        $RecoveryList = $this->ProductModel->onlyTrashed()->order('deletetime', 'desc')
            ->paginate(5, false, ['query' => Request::instance()->param()]);

        if ($this->request->isAjax()) {
            $action = $this->request->param('action');
            // 彻底删除
            if ($action == 'del') {
                $id = $this->request->param('id');
                $post = $this->ProductModel->onlyTrashed()->find($id);
                if ($post == null) {
                    $this->error('该商品无法彻底删除');
                }
                // halt('123');
                $res = $this->ProductModel->destroy($id, true);
                if ($res == false) {
                    $this->error('删除失败');
                }
                $this->success('该商品已经彻底删除');
            }
            // 恢复
            if ($action == 'return') {
                $id = $this->request->param('id');
                $post = $this->ProductModel->onlyTrashed()->find($id);
                if ($post == null) {
                    $this->error('该商品无法恢复');
                }
                // $this->success('该分类可以恢复');
                $data = [
                    'id' => $id,
                    'deletetime' => null
                ];
                $res = $this->ProductModel->isUpdate(true)->save($data);
                if ($res == false) {
                    $this->error('恢复失败');
                }
                $this->success('恢复成功');
            }
            // 批量删除
            if ($action == 'delAll') {
                $params = $this->request->param();
                $ids = implode(',', $params['list']);
                // halt($ids);
                $data = [
                    'id' => $ids,
                    'deletetime' => null
                ];
                $res = $this->ProductModel->destroy($ids, true);
                if (!$res) {
                    $this->error('批连删除失败');
                }
                $this->success("批量删除成功", null, null, 2);
            }
            // 批量恢复
            if ($action == 'returnAll') {
                $params = $this->request->param();
                $ids = implode(',', $params['list']);
                $data = [];
                foreach ($params['list'] as $key => $item) {
                    $arr['id'] = $item;
                    $arr['deletetime'] = null;
                    array_push($data, $arr);
                }
                // halt($data);
                $res = $this->ProductModel->isUpdate(true)->saveAll($data);
                if (!$res) {
                    $this->error('批量恢复失败');
                }
                $this->success("批量恢复成功", null, null, 2);
            }
        }
        $navTitle = '商品管理';
        $navSmall = '回收站';
        return $this->fetch('', [
            'navTitle' => $navTitle,
            'navSmall' => $navSmall,
            'RecoveryList' => $RecoveryList,
        ]);
    }
}
